package com.niit.servlet;

import com.niit.pojo.User;
import com.niit.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Date;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if ("findById".equals(action)) {
            // 处理根据ID查询用户的请求
            String id = req.getParameter("id");
            if (id != null) {
                try {
                    int userId = Integer.parseInt(id);
                    User user = userService.findUserById(userId);

                    resp.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = resp.getWriter();
                    if (user != null) {
                        // 这里可以使用JSON库将User对象转换为JSON，简化示例中直接拼接
                        out.write("{\"id\":" + user.getId() + ",");
                        out.write("\"userName\":\"" + user.getUserName() + "\",");
                        out.write("\"email\":\"" + user.getEmail() + "\",");
                        out.write("\"phone\":\"" + user.getPhone() + "\",");
                        out.write("\"role\":\"" + user.getRole() + "\",");
                        out.write("\"createTime\":\"" + user.getCreateTime() + "\"}");
                    } else {
                        out.write("{}");
                    }
                    out.flush();
                    out.close();
                } catch (NumberFormatException e) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的用户ID");
                }
                return;
            }
        }

        // 原有查询逻辑...
        String keyword = req.getParameter("keyword");
        String statusParam = req.getParameter("status");
        Integer status = null;

        if (statusParam != null && !statusParam.isEmpty()) {
            try {
                status = Integer.parseInt(statusParam);
            } catch (NumberFormatException e) {
                // 忽略无效的状态参数
            }
        }

        List<User> users;
        if (keyword != null && !keyword.isEmpty()) {
            // 执行搜索
            users = userService.searchUsers(keyword, status);
            req.setAttribute("searchKeyword", keyword);
        } else {
            // 获取所有用户
            users = userService.findUsers();
        }

        req.setAttribute("users", users);
        req.getRequestDispatcher("user.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");

        if ("updateStatus".equals(action)) {
            // 处理更新用户状态的请求
            String id = req.getParameter("id");
            String status = req.getParameter("status");

            if (id != null && status != null) {
                try {
                    int userId = Integer.parseInt(id);
                    int userStatus = Integer.parseInt(status);
                    boolean result = userService.updateStatus(userId, userStatus);
                    resp.getWriter().write(result ? "1" : "0");
                } catch (NumberFormatException e) {
                    resp.getWriter().write("0");
                }
                return;
            }
        }   else {
            // 处理添加用户的请求
            String username = req.getParameter("username");
            String email = req.getParameter("email");
            String pwd = req.getParameter("pwd");
            String phone = req.getParameter("phone");
            String role = req.getParameter("role");

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = dateFormat.format(new Date());

            User user = new User();
            user.setUserName(username);
            user.setEmail(email);
            user.setPwd(pwd);
            user.setPhone(phone);
            user.setRole(role);
            user.setCreateTime(createTime);

            if (username == null || pwd == null || role == null) {
                req.setAttribute("error", "用户名、密码、角色为必填项");
                req.getRequestDispatcher("user_form.jsp").forward(req, resp);
                return;
            }

            int result = userService.addUser(user);

            if (result > 0) {
                resp.sendRedirect(req.getContextPath() + "/user");
            } else {
                // 添加失败，返回错误信息
                req.setAttribute("error", "添加用户失败");
                req.getRequestDispatcher("user_form.jsp").forward(req, resp);
            }
        }
    }
}
